<template>
  <div class="sensor-detail-chart-container">
    <canvas :id="`sensorDetailCanvas-${sensorId}`"></canvas>
    <p v-if="chartError" class="chart-error">{{ chartError }}</p>
    <p v-if="chartLoading" class="chart-loading">数据加载中...</p>
    <p
      v-if="!chartLoading && !chartError && (!chartData.labels || chartData.labels.length === 0)"
      class="chart-no-data"
    >
      暂无数据
    </p>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import Chart from 'chart.js/auto' // 确保正确导入 Chart.js
import { Chart as ChartJS } from 'chart.js'
import annotationPlugin from 'chartjs-plugin-annotation'
ChartJS.register(annotationPlugin)

const props = defineProps({
  sensorId: {
    // 被点击的传感器ID，例如 'FIC1001'
    type: String,
    required: true,
  },
  deviceName: {
    // 所属装置名称，用于调试或未来扩展
    type: String,
    required: true,
  },
})

let chartInstance = null // Chart.js 实例
let refreshInterval = null // 用于实时数据刷新定时器

const chartLoading = ref(false)
const chartError = ref(null)
const chartData = ref({ labels: [], historicalData: [], predictedData: [], thresholds: {} }) // 存储所有数据和阈值

// 预警/警戒阈值 (如果后端接口没有返回阈值，则使用这些默认值)
const FALLBACK_THRESHOLDS = {
  FIC1001: { lowerAlert: 45, upperAlert: 85, lowerWarn: 50, upperWarn: 80 },
  FIC1002: { lowerAlert: 8, upperAlert: 22, lowerWarn: 10, upperWarn: 20 },
  PIC1003: { lowerAlert: 4, upperAlert: 16, lowerWarn: 5, upperWarn: 15 },
  FI615: { lowerAlert: 55, upperAlert: 80, lowerWarn: 60, upperWarn: 75 },
  TE203: { lowerAlert: 25, upperAlert: 50, lowerWarn: 30, upperWarn: 45 },
  LI301: { lowerAlert: 55, upperAlert: 95, lowerWarn: 60, upperWarn: 90 },
  default: { lowerAlert: 20, upperAlert: 80, lowerWarn: 30, upperWarn: 70 }, // 默认值
}

/**
 * 销毁 Chart.js 实例。
 */
const destroyChart = () => {
  if (chartInstance) {
    chartInstance.destroy()
    chartInstance = null
    console.log(`SensorDetailChart: Chart instance for ${props.sensorId} destroyed.`)
  }
}

/**
 * 停止实时刷新定时器。
 */
const stopRefreshInterval = () => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
    console.log(`SensorDetailChart: Refresh interval for ${props.sensorId} stopped.`)
  }
}

/**
 * 获取传感器数据 (历史 + 预测) 及阈值。
 * 直接从后端接口 `/api/sensors/{sensorId}/data` 获取，不再包含前端模拟逻辑。
 */
const fetchSensorData = async () => {
  chartLoading.value = true
  chartError.value = null // 清除之前的错误
  // chartData.value = { labels: [], historicalData: [], predictedData: [], thresholds: {} }; // 可以在这里清空，或者在 finally 块中统一处理

  let labels = []
  let historicalData = []
  let predictedData = []
  let thresholds = {}

  try {
    console.log(
      `SensorDetailChart: Fetching data for point: ${props.sensorId} via /api/sensors/${props.sensorId}/data.`,
    )
    const response = await fetch(`/api/sensors/${props.sensorId}/data`)

    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`HTTP error! status: ${response.status} - ${errorText}`)
    }
    const result = await response.json()

    if (!result.success || !Array.isArray(result.history) || !Array.isArray(result.predict)) {
      throw new Error(`API returned invalid data or success: false.`)
    }

    // 解析历史数据
    labels = result.history.map((item) =>
      new Date(item.datetime).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      }),
    )
    historicalData = result.history.map((item) => item.value)

    // 解析预测数据
    const rawPredictedLabels = result.predict.map((item) =>
      new Date(item.datetime).toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      }),
    )
    const rawPredictedData = result.predict.map((item) => item.value)

    // 合并 X 轴标签：历史和预测的所有时间点
    let allLabels = [...labels] // Start with historical labels
    rawPredictedLabels.forEach((label) => {
      if (!allLabels.includes(label)) {
        // Avoid adding duplicate labels
        allLabels.push(label)
      }
    })
    // Sort all labels by time
    allLabels.sort((a, b) => {
      const dateA = new Date(`2000/01/01 ${a}`) // Use a dummy date for sorting time strings
      const dateB = new Date(`2000/01/01 ${b}`)
      return dateA.getTime() - dateB.getTime()
    })

    // Prepare predictedData for Chart.js: fill with nulls so prediction starts visually after history
    let chartPredictedData = Array(allLabels.length).fill(null) // Array spanning all labels

    // Fill historical values into the predicted data array at their correct indices
    labels.forEach((label, index) => {
      const labelIndex = allLabels.indexOf(label)
      if (labelIndex !== -1) {
        chartPredictedData[labelIndex] = historicalData[index]
      }
    })

    // Then, overlay actual prediction values onto their correct indices
    rawPredictedLabels.forEach((label, index) => {
      const labelIndex = allLabels.indexOf(label)
      if (labelIndex !== -1) {
        chartPredictedData[labelIndex] = rawPredictedData[index]
      }
    })

    // Get thresholds, fallback if backend doesn't provide them
    thresholds =
      result.thresholds || FALLBACK_THRESHOLDS[props.sensorId] || FALLBACK_THRESHOLDS['default']

    chartData.value = {
      labels: allLabels,
      historicalData: historicalData, // This is the historical data set
      predictedData: chartPredictedData, // This is the combined historical + predicted data set (with nulls)
      thresholds: thresholds,
    }
    console.log(`SensorDetailChart: Data loaded for ${props.sensorId}.`)
  } catch (error) {
    console.error(`SensorDetailChart: Error fetching data for ${props.sensorId}:`, error)
    chartError.value = `数据加载失败。${error.message}`
    // On error, ensure chartData is empty so "No data" message appears
    chartData.value = { labels: [], historicalData: [], predictedData: [], thresholds: {} }
  } finally {
    chartLoading.value = false
  }
}

/**
 * 绘制 Chart.js 图表。
 */
const drawChart = () => {
  destroyChart() // 每次绘制前销毁旧图表实例

  const canvasId = `sensorDetailCanvas-${props.sensorId}`
  const canvas = document.getElementById(canvasId)
  if (!canvas) {
    console.warn(`SensorDetailChart: Canvas element ${canvasId} not found. Skipping chart draw.`)
    stopRefreshInterval()
    return
  }
  const ctx = canvas.getContext('2d')
  if (!ctx) {
    console.error(`SensorDetailChart: Could not get 2D context for ${canvasId}.`)
    stopRefreshInterval()
    return
  }

  // 如果 chartData 中没有数据，则清空 canvas 并显示“暂无数据”提示
  if (!chartData.value.labels || chartData.value.labels.length === 0) {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.font = '16px Arial'
    ctx.fillStyle = '#888'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', canvas.width / 2, canvas.height / 2)
    stopRefreshInterval() // 没有数据，停止刷新
    return
  }

  const currentThresholds =
    chartData.value.thresholds ||
    FALLBACK_THRESHOLDS[props.sensorId] ||
    FALLBACK_THRESHOLDS['default']
  console.log('DEBUG: Chart初始化前最终的currentThresholds:', currentThresholds) // 添加这行
  console.log(
    'DEBUG: lowerAlert:',
    currentThresholds.lowerAlert,
    '类型:',
    typeof currentThresholds.lowerAlert,
  )
  console.log(
    'DEBUG: upperAlert:',
    currentThresholds.upperAlert,
    '类型:',
    typeof currentThresholds.upperAlert,
  )

  // 如果在这里看到 'undefined' 或非数字类型，那就是问题所在。
  if (
    typeof currentThresholds.lowerAlert !== 'number' ||
    typeof currentThresholds.upperAlert !== 'number'
  ) {
    console.warn('DEBUG: lowerAlert 或 upperAlert 不是数字，标注可能无法绘制。')
  }

  // 计算Y轴范围包括数据和阈值线
  const allNumericalData = [
    ...chartData.value.historicalData,
    ...chartData.value.predictedData.filter((v) => v !== null),
  ].filter((v) => typeof v === 'number')

  let minValue = allNumericalData.length > 0 ? Math.min(...allNumericalData) : 0
  let maxValue = allNumericalData.length > 0 ? Math.max(...allNumericalData) : 100

  // 确保阈值线也包含在 Y 轴范围内
  if (currentThresholds.lowerAlert !== undefined) {
    console.log('---------------------lowerAlert', currentThresholds.lowerAlert)
    minValue = Math.min(minValue, currentThresholds.lowerAlert)
  }

  if (currentThresholds.upperAlert !== undefined) {
    maxValue = Math.max(maxValue, currentThresholds.upperAlert)
    console.log('---------------------upperAlert', currentThresholds.upperAlert)
  }

  // 移除 lowerWarn 和 upperWarn 的 min/max 范围计算，因为它们不再绘制
  // if (currentThresholds.lowerWarn !== undefined) minValue = Math.min(minValue, currentThresholds.lowerWarn);
  // if (currentThresholds.upperWarn !== undefined) maxValue = Math.max(maxValue, currentThresholds.upperWarn);

  if (minValue === maxValue) {
    minValue -= 5
    maxValue += 5
  }

  const padding = (maxValue - minValue) * 0.1
  console.log('DEBUG: 计算出的Y轴范围: min=', minValue - padding, 'max=', maxValue + padding)

  chartInstance = new Chart(ctx, {
    type: 'line',
    data: {
      labels: chartData.value.labels,
      datasets: [
        {
          label: '历史数据',
          data: chartData.value.historicalData,
          borderColor: 'rgb(54, 162, 235)', // 蓝色
          backgroundColor: 'rgba(54, 162, 235, 0.1)',
          borderWidth: 2,
          tension: 0.3,
          pointRadius: 0,
          fill: false,
          spanGaps: false, // 历史数据不应该有 nulls
        },
        {
          label: '预测数据',
          data: chartData.value.predictedData,
          borderColor: 'rgb(75, 192, 192)', // 绿色
          backgroundColor: 'rgba(75, 192, 192, 0.1)',
          borderWidth: 2,
          tension: 0.3,
          pointRadius: 0,
          fill: false,
          spanGaps: true, // 处理预测数据中的 null 值，使其在历史数据后连接
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { display: true, position: 'top' },
        title: {
          display: true,
          text: `传感器 ${props.sensorId} 趋势分析`,
          font: { size: 16 },
        },
        annotation: {
          annotations: {
            lowerAlert:
              currentThresholds.lowerAlert !== undefined
                ? {
                    type: 'line',
                    yMin: currentThresholds.lowerAlert,
                    yMax: currentThresholds.lowerAlert,
                    borderColor: 'red',
                    borderWidth: 2,
                    borderDash: [6, 6],
                    label: {
                      enabled: true,
                      content: '低警戒',
                      position: 'start',
                      backgroundColor: 'rgba(255, 0, 0, 0.8)',
                      color: 'white',
                      font: { size: 10 },
                    },
                  }
                : {},
            upperAlert:
              currentThresholds.upperAlert !== undefined
                ? {
                    type: 'line',
                    yMin: currentThresholds.upperAlert,
                    yMax: currentThresholds.upperAlert,
                    borderColor: 'red',
                    borderWidth: 2,
                    borderDash: [6, 6],
                    label: {
                      enabled: true,
                      content: '高警戒',
                      position: 'end',
                      backgroundColor: 'rgba(255, 0, 0, 0.8)',
                      color: 'white',
                      font: { size: 10 },
                    },
                  }
                : {},
          },
        },
      },
      scales: {
        x: {
          display: true,
          title: { display: true, text: '时间' },
          ticks: { autoSkip: true, maxTicksLimit: 10 },
        },
        y: {
          display: true,
          title: { display: true, text: '参数值' },
          min: minValue - padding,
          max: maxValue + padding,
        },
      },
      animation: { duration: 0 }, // 关闭动画
    },
  })
}

/**
 * 启动实时刷新定时器。
 */
const startRefreshInterval = () => {
  stopRefreshInterval() // 清除任何现有定时器
  refreshInterval = setInterval(async () => {
    console.log(`SensorDetailChart: Auto-refreshing data for ${props.sensorId}`)
    await fetchSensorData() // 获取新数据
    drawChart() // 使用新数据重新绘制图表
  }, 10000) // 每1秒刷新一次
  console.log(`SensorDetailChart: Refresh interval for ${props.sensorId} started.`)
}

onMounted(async () => {
  await fetchSensorData()
  await nextTick() // 确保 canvas DOM 完全渲染后再尝试绘制
  drawChart()
  startRefreshInterval() // Start refreshing
})

watch(
  () => props.sensorId,
  async (newSensorId) => {
    if (newSensorId) {
      console.log(`SensorDetailChart: sensorId prop changed to ${newSensorId}. Fetching new data.`)
      stopRefreshInterval() // 停止旧定时器
      await fetchSensorData()
      await nextTick()
      drawChart()
      startRefreshInterval() // 为新传感器启动刷新
    }
  },
)

onUnmounted(() => {
  stopRefreshInterval() // 组件卸载时停止刷新
  destroyChart()
})
</script>

<style scoped>
.sensor-detail-chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.sensor-detail-chart-container canvas {
  width: 100% !important;
  height: 100% !important; /* Make canvas fill its container */
}

.chart-error,
.chart-loading,
.chart-no-data {
  position: absolute;
  font-size: 0.9em;
  color: #999;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  width: 100%;
}
.chart-error {
  color: #dc3545;
}
.chart-loading {
  color: #007bff;
}
</style>
